package com.mvc.web.main.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mvc.web.main.service.MainService;
import com.mvc.web.main.vo.KeyValueVo;
import com.mvc.web.main.vo.SerachConditionVo;
import com.mvc.web.user.service.UserService;
import com.mvc.web.user.vo.UserVo;

@Controller
public class MainController {
	
	private final String MAIN_INDEX = "main/index";
	
	private static Log log = LogFactory.getLog(MainController.class);

	@Autowired
	private MainService mainService;
	
	@Autowired
	private UserService userService;
	
	
	@RequestMapping("/")
	public ModelAndView index(HttpServletRequest request,SerachConditionVo vo,ModelMap map){
		ModelAndView mav = new ModelAndView(MAIN_INDEX);
		if (vo.getCurrentPage() == null) {
			vo.setCurrentPage(1);
        }
        if (vo.getLimit() == null) {
            vo.setLimit(20);
        }
        //获取省份、城市
        List<KeyValueVo> province = this.mainService.getProvinceList();
        List<KeyValueVo> city = this.mainService.getCityList(vo.getProvince());
        //获取用户列表
        vo.setStart((vo.getCurrentPage() - 1) * vo.getLimit());
        UserVo user = (UserVo) request.getSession().getAttribute("user");
        if(user != null){
        	vo.setId(user.getId());
        }
        List<UserVo> list = userService.getList(vo);
        long count        = userService.getCount(vo);
        long totalPages = count % vo.getLimit() == 0 ? count / vo.getLimit() : count / vo.getLimit() + 1;
        //返回数据
        map.put("list", list);
        map.put("province",province);
        map.put("city",city);
        map.put("pageUrl", "/");
        map.put("currentPage", vo.getCurrentPage());
        map.put("totalPages", totalPages);
        map.put("limit", vo.getLimit());
        map.put("condition", vo);
        map.put("user", user);
        log.info("打印信息");
        
        log.error("错误信息");
        return mav;
	}
	
	@RequestMapping("/base/getCity")
	@ResponseBody
	public List<KeyValueVo> getCity(Integer provinceId){
		return this.mainService.getCityList(provinceId);
	}
	
}
